package com.feng.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置类 发布确认 （高级）
 */
@Configuration
public class ConfirmConfig {
    //交换机
    public static final String CONFIRM_EXCHANGE_NAME = "confirm_exchange";

    //队列
    public static final String CONFIRM_QUEUE_NAME = "confirm_queue";

    //routingkey
    public static final String CONFIRM_ROUTING_KEY = "confirm_routingkey";

    //备份交换机
    public static final String BACKUP_EXCHANGE_NAME = "backup_exchange";

    //备份队列
    public static final String BACKUP_QUEUE_NAME = "backup_queue";

    //报警队列
    public static final String WARNING_QUEUE_NAME = "warning_queue";

    //声明交换机
    @Bean("confirmExchange")
    public DirectExchange confirmExchange(){
//        return new DirectExchange(CONFIRM_EXCHANGE_NAME);
        //绑定备份交换机只能用下面的方法
        return ExchangeBuilder
                .directExchange(CONFIRM_EXCHANGE_NAME)
                .durable(true)
                .withArgument("alternate-exchange",BACKUP_EXCHANGE_NAME)
                .build();
    }

    //声明队列
    @Bean("confirmQueue")
    public Queue confirmQueue(){
        //方式一
//        return QueueBuilder.durable(CONFIRM_QUEUE_NAME).build();
        //方式二
        return new Queue(CONFIRM_QUEUE_NAME);
    }

    //绑定队列和交换机
    @Bean
    public Binding confirmQueueExchange(@Qualifier("confirmQueue")Queue queue,
                                        @Qualifier("confirmExchange")DirectExchange directExchange){
        return BindingBuilder.bind(queue).to(directExchange).with(CONFIRM_ROUTING_KEY);
    }

    //备份交换机
    @Bean("backupExchange")
    public FanoutExchange backupExchange(){
        return new FanoutExchange(BACKUP_EXCHANGE_NAME);
    }

    //备份队列
    @Bean("backupQueue")
    public Queue backupQueue(){
        return new Queue(BACKUP_QUEUE_NAME);
    }

    //警告队列
    @Bean("warnQueue")
    public Queue warnQueue(){
        return QueueBuilder.durable(WARNING_QUEUE_NAME).build();
    }

    //绑定备份交换机和备份队列
    @Bean
    public Binding backupQueueExchange(@Qualifier("backupQueue")Queue backupQueue,
                                       @Qualifier("backupExchange")FanoutExchange fanoutExchange){
        return BindingBuilder.bind(backupQueue).to(fanoutExchange);
    }
    //绑定备份交换机和警告队列
    @Bean
    public Binding warnQueueExchange(@Qualifier("warnQueue")Queue warnQueue,
                                       @Qualifier("backupExchange")FanoutExchange fanoutExchange){
        return BindingBuilder.bind(warnQueue).to(fanoutExchange);
    }
}
